<template>
  <el-dialog title="登录"
             class="login-dialog"
             :visible.sync="showDialog"
             :close-on-click-modal="false"
             :close-on-press-escape="false"
             :show-close="false">
    <el-form :model="form" label-width="80px">
      <el-form-item label="账号" required>
        <el-input v-model="form.username"/>
      </el-form-item>
      <el-form-item label="密码" required>
        <el-input type="password" v-model="form.password"/>
      </el-form-item>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button type="primary" @click="submit">登录</el-button>
    </div>
  </el-dialog>
</template>

<script>
  export default {
    name: 'login',
    data() {
      return {
        showDialog: false,
        form: {username: '', password: ''},
      };
    },
    methods: {
      show() {
        this.showDialog = true;
      },
      close() {
        this.showDialog = false;
      },
      async submit() {
        const res = await this.$http.post('/api/user/login', this.form);
        if (res instanceof Error)
          return this.$alert(res.message, {type: 'error'});
        this.$emit('success', res.data);
        this.close();
      },
      async checkLogin() {
        const res = await this.$http.get('/api/user/check-login');
        if (res instanceof Error)
          return this.show();
        this.$emit('success', res.data);
      },
    },
    mounted() {
      this.checkLogin();
    },
  };
</script>

<style>
  .login-dialog > .el-dialog {
    width: 480px;
  }
</style>